<?php


namespace plugins\user\api\controller;


use app\controller\frontend\BaseController;
use app\model\PhoneCode;
use app\service\sms\ALiSms;
use think\facade\Cache;
use think\facade\Env;

class SmsController extends BaseController
{
    /**
     * 发送短信验证码
     * @return \think\response\Json
     */
    public function smsSend()
    {
        $phone = $this->request->param('mobile/s',"");//号码
        if(empty($phone)){
            return jsonReturn(-1, lang('请输入号码'));
        }
        $key = $phone . '_login';
        if(Cache::has($key)!=false){
            return jsonReturn(-2,  lang('验证码未到期,请稍后再发'));
        }
        $data = [
            'phone' => $phone,
            'code' => random_code_type(6, 'number'),
            'seller_id' => $this->sellerId,
            'expired_time' => date('Y-m-d H:i:s', time() + 5 * 60), // 登录验证码5分钟有效
        ];
        Cache::set($key, time(), 5 * 60);
        //保存发送code记录
        $codeModel = new PhoneCode();
        $codeModel->insertGetId([
            'phone' => $data['phone'],
            'code' => $data['code'],
            'expired_time' => $data['expired_time']
        ]);
        if (Env::get('APP_DEBUG')) {
            return jsonReturn(0, lang('发送成功'), $data);
        }
        $res = ALiSms::sendOneAuthMsg($data);
        if ($res['code'] != 0) {
            return json($res);
        }
        return jsonReturn(0, lang('发送成功'), ['phone' => $phone]);
    }

}